package com.cw.common.method;

import com.alibaba.fastjson.JSON;
import com.cw.entity.*;
import com.cw.vo.ViewRJSSVO;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;


public class SendCardMsg {

    public static String GetJson(MsgInfo msgInfo) {
        Map<String, Object> map2 = new HashMap<String, Object>();
        //消息标题
        String title = msgInfo.getTitle();
        String description = "";
        //获取当前的日期
        Date date = new Date();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String time = df.format(date);

        //信息主体
        description = description + "<div class=\"gray\">" + time + "</div>";
        description =
                description + "<div class=\"normal\">患者姓名：" + msgInfo.getName() + "(" + msgInfo.getDeptName() + ")" + "</div>";
        description = description + "<div class=\"normal\">患者手机号：" + msgInfo.getLinkmanTel() + "</div>";
        description =
                description + "<div class=\"normal\">已安排至" + msgInfo.getNurseCellName() + "病区" + msgInfo.getBedNum() + "床位</div>";
        description = description + "<div class=\"highlight\">" + "请联系患者尽快办理住院手续,并将病情告知主管医生和护士站</div>";
        //详情网址
        String url = "http://www.sdfey.com";
        //按钮内容
        String btntxt = "";
        map2.put("title", title);
        map2.put("description", description);
        map2.put("url", url);
        map2.put("btntxt", btntxt);
        //先将text的内容转化为jason字符串
        String mapJson2 = JSON.toJSONString(map2);
        Map<String, Object> map = new HashMap<String, Object>();
        //后期改动态
        map.put("touser", msgInfo.getWechatAccountCode());
        map.put("msgtype", "textcard");
        map.put("agentid", "1000028");
        map.put("textcard", mapJson2);
        //map转换为json形式
        String mapJson = JSON.toJSONString(map);
        //json串格式化，成为普通的string串
        String newString = StringEscapeUtils.unescapeJavaScript(mapJson);
        //但是普通的string串使用map<string,string>拼接，string两边会有双引号
        String s3 = newString.replace(":\"{", ":{");
        //修改，把第二层json外面多余的双引号去除
        String s4 = s3.replace("}\"", "}");
        String ans = "msg=" + s4;//给出的接口已msg=这个格式接受json格式的消息
        return ans;//返回的ans为最终所需要的串
    }


    public static WeChatLog send2(MsgInfo msgInfo) throws IOException {
        String textMsg = GetJson(msgInfo);
        WeChatLog weChatLog = new WeChatLog();
        weChatLog.setWeChatRequestMsg(textMsg);
        weChatLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        weChatLog.setWeChatCode(msgInfo.getWechatAccountCode());
        weChatLog.setDoctorCode(msgInfo.getEmplCode());
        weChatLog.setDoctorName(msgInfo.getEmplName());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //指定接口发送post请求
        HttpPost httpPost = new HttpPost("http://172.16.9.241/proxy/weworksendmsg.php");
        //增加header
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httpPost.setEntity(se);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            weChatLog.setResponseType("success");
            weChatLog.setResponseMsg(result);
        } else {
            weChatLog.setResponseType("fail");
        }
        // 关闭
        httpClient.close();
        response.close();
        return weChatLog;
    }

    public static WeChatLog send4(MsgInfo msgInfo) throws IOException {
        String textMsg = GetJson3(msgInfo);
        WeChatLog weChatLog = new WeChatLog();
        weChatLog.setWeChatRequestMsg(textMsg);
        weChatLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        weChatLog.setWeChatCode(msgInfo.getWechatAccountCode());
        weChatLog.setDoctorCode(msgInfo.getEmplCode());
        weChatLog.setDoctorName(msgInfo.getEmplName());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //指定接口发送post请求
        HttpPost httpPost = new HttpPost("http://172.16.9.241/proxy/weworksendmsg.php");
        //增加header
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httpPost.setEntity(se);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            weChatLog.setResponseType("success");
            weChatLog.setResponseMsg(result);
        } else {
            weChatLog.setResponseType("fail");
        }
        // 关闭
        httpClient.close();
        response.close();
        return weChatLog;
    }

    private static String GetJson3(MsgInfo msgInfo) {
        Map<String, Object> map2 = new HashMap<String, Object>();
        //消息标题
        String title = msgInfo.getTitle();
        String description = "";
        //获取当前的日期
        Date date = new Date();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String time = df.format(date);

        //信息主体
        description = description + "<div class=\"gray\">" + time + "</div>";
        description = description + "<div class=\"normal\">" + msgInfo.getEmplName() + "医生：" + "</div>";
        description =
                description + "<div class=\"normal\">患者信息：" + msgInfo.getName() + "(申请病区：" + msgInfo.getNurseCellName() +
                        ")</div>";
        description = description + "<div class=\"normal\">入院诊断：" + msgInfo.getDiagName() + "</div>";
        description = description + "<div class=\"normal\">" + msgInfo.getRemark() + "</div>";
//        description = description + "<div class=\"highlight\">" + "请联系患者尽快办理住院手续,并将病情告知护士站</div>";
        //详情网址
        String url = "http://www.sdfey.com";
        //按钮内容
        String btntxt = "";
        map2.put("title", title);
        map2.put("description", description);
        map2.put("url", url);
        map2.put("btntxt", btntxt);
        //先将text的内容转化为jason字符串
        String mapJson2 = JSON.toJSONString(map2);
        Map<String, Object> map = new HashMap<String, Object>();
        //后期改动态
        map.put("touser", msgInfo.getWechatAccountCode());
        map.put("msgtype", "textcard");
        map.put("agentid", "1000028");
        map.put("textcard", mapJson2);
        //map转换为json形式
        String mapJson = JSON.toJSONString(map);
        //json串格式化，成为普通的string串
        String newString = StringEscapeUtils.unescapeJavaScript(mapJson);
        //但是普通的string串使用map<string,string>拼接，string两边会有双引号
        String s3 = newString.replace(":\"{", ":{");
        //修改，把第二层json外面多余的双引号去除
        String s4 = s3.replace("}\"", "}");
        String ans = "msg=" + s4;//给出的接口已msg=这个格式接受json格式的消息
        return ans;//返回的ans为最终所需要的串
    }


    //短信发送消息

    /**
     * msgInfo 参数
     * flag 0:预约  1:取消
     */
    public static TelMessageLog sendTelMessage(MsgInfo msgInfo, Integer flag) throws IOException {
        StringBuilder telMessage = new StringBuilder("尊敬的" + msgInfo.getName() + "：您已成功预约" + msgInfo.getYardName() +
                "院区" + msgInfo.getNurseCellName() + msgInfo.getBedNum() + "床," + "请于今日16:00" +
                "前至苏州大学附属第二医院住院处办理入院手续，若不能准时赶到请在16:00前联系（18061930170）！");
        if (flag == 1) {
            telMessage = new StringBuilder("尊敬的" + msgInfo.getName() + "：您预约的床位已取消.取消原因:" + msgInfo.getRemark());
        }

        TelMessageLog telMessageLog = new TelMessageLog();
        telMessageLog.setRequestMsg(telMessage.toString());
        telMessageLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        telMessageLog.setLinkPhoneTel(msgInfo.getLinkmanTel());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(
                "http://172.16.0.171:51008/sms/sms_send" +
                        ".php?service=cwgl&username=cwgl&password=feycwgl20220215&RPhone=" + telMessageLog.getLinkPhoneTel() + "&PostInfo=" + telMessageLog.getRequestMsg());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            telMessageLog.setResponseType("success");
            telMessageLog.setResponseMsg(result);
        } else {
            telMessageLog.setResponseType("fail");
        }
        httpClient.close();
        response.close();
        return telMessageLog;
    }

    public static TelMessageLog sendTelMessage2(MsgInfo msgInfo, String msgContent, int flag) throws IOException {
        StringBuilder telMessage = new StringBuilder(msgContent);
        if (flag == 1) {
            telMessage = new StringBuilder("尊敬的" + msgInfo.getName() + "：您的预约已取消!");
        }

        TelMessageLog telMessageLog = new TelMessageLog();
        telMessageLog.setRequestMsg(telMessage.toString());
        telMessageLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        telMessageLog.setLinkPhoneTel(msgInfo.getLinkmanTel());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(
                "http://172.16.0.171:51008/sms/sms_send" +
                        ".php?service=cwgl&username=cwgl&password=feycwgl20220215&RPhone=" + telMessageLog.getLinkPhoneTel() + "&PostInfo=" + telMessageLog.getRequestMsg());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            telMessageLog.setResponseType("success");
            telMessageLog.setResponseMsg(result);
        } else {
            telMessageLog.setResponseType("fail");
        }
        httpClient.close();
        response.close();
        return telMessageLog;
    }

    public static WeChatLog send3(MsgInfo msgInfo, PatientBedMiddleRjbf appointmentMsg) throws IOException {
        String textMsg = GetJson2(msgInfo, appointmentMsg);
        WeChatLog weChatLog = new WeChatLog();
        weChatLog.setWeChatRequestMsg(textMsg);
        weChatLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        weChatLog.setWeChatCode(msgInfo.getWechatAccountCode());
        weChatLog.setDoctorCode(msgInfo.getEmplCode());
        weChatLog.setDoctorName(msgInfo.getEmplName());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //指定接口发送post请求
        HttpPost httpPost = new HttpPost("http://172.16.9.241/proxy/weworksendmsg.php");
        //增加header
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httpPost.setEntity(se);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            weChatLog.setResponseType("success");
            weChatLog.setResponseMsg(result);
        } else {
            weChatLog.setResponseType("fail");
        }
        // 关闭
        httpClient.close();
        response.close();
        return weChatLog;
    }


    private static String GetJson2(MsgInfo msgInfo, PatientBedMiddleRjbf appointmentMsg) {
        Map<String, Object> map2 = new HashMap<String, Object>();
        //消息标题
        String title = msgInfo.getTitle();
        String description = "";
        //获取当前的日期
        Date date = new Date();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String time = df.format(date);
        // 获取年月日
        // 预约时间
        Date appointmentTime = appointmentMsg.getAppointmentTime();
        String appointmentClasses = appointmentMsg.getAppointmentClasses();
        // 获取年  月  日
        ZoneId timeZone = ZoneId.systemDefault();
        LocalDate getDate = appointmentTime.toInstant().atZone(timeZone).toLocalDate();
        // 年
        int year = getDate.getYear();
        // 月
        int month = getDate.getMonthValue();
        // 日
        int day = getDate.getDayOfMonth();
        String text = "您的病人" + msgInfo.getName() + "已预约" + year + "年" + month + "月" + day + "日来我院进行" + ("1".equals(
                appointmentMsg.getType()) ? "日间手术" : "日间输注") + "治疗，如取消或调整请电话告知日间治疗中心（4215或4212），患者迟到请重新预约。如无特殊情况无需回复。";

        //信息主体
        description = description + "<div class=\"gray\">" + time + "</div>";
        description = description + "<div class=\"normal\">" + text + "</div>";
        //详情网址
        String url = "http://www.sdfey.com";
        //按钮内容
        String btntxt = "";
        map2.put("title", title);
        map2.put("description", description);
        map2.put("url", url);
        map2.put("btntxt", btntxt);
        //先将text的内容转化为jason字符串
        String mapJson2 = JSON.toJSONString(map2);
        Map<String, Object> map = new HashMap<String, Object>();
        //后期改动态
        map.put("touser", msgInfo.getWechatAccountCode());
        map.put("msgtype", "textcard");
        map.put("agentid", "1000028");
        map.put("textcard", mapJson2);
        //map转换为json形式
        String mapJson = JSON.toJSONString(map);
        //json串格式化，成为普通的string串
        String newString = StringEscapeUtils.unescapeJavaScript(mapJson);
        //但是普通的string串使用map<string,string>拼接，string两边会有双引号
        String s3 = newString.replace(":\"{", ":{");
        //修改，把第二层json外面多余的双引号去除
        String s4 = s3.replace("}\"", "}");
        String ans = "msg=" + s4;//给出的接口已msg=这个格式接受json格式的消息
        return ans;//返回的ans为最终所需要的串
    }

    public static WeChatLog send5(MsgInfo msgInfo) throws IOException {
        String textMsg = GetJson5(msgInfo);
        WeChatLog weChatLog = new WeChatLog();
        weChatLog.setWeChatRequestMsg(textMsg);
        weChatLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        weChatLog.setWeChatCode(msgInfo.getWechatAccountCode());
        weChatLog.setDoctorCode(msgInfo.getEmplCode());
        weChatLog.setDoctorName(msgInfo.getEmplName());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //指定接口发送post请求
        HttpPost httpPost = new HttpPost("http://172.16.9.241/proxy/weworksendmsg.php");
        //增加header
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httpPost.setEntity(se);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            weChatLog.setResponseType("success");
            weChatLog.setResponseMsg(result);
        } else {
            weChatLog.setResponseType("fail");
        }
        // 关闭
        httpClient.close();
        response.close();
        return weChatLog;
    }

    private static String GetJson5(MsgInfo msgInfo) {
        Map<String, Object> map2 = new HashMap<String, Object>();
        //消息标题
        String title = msgInfo.getTitle();
        String description = "";
        //获取当前的日期
        Date date = new Date();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String time = df.format(date);

        //信息主体
        description = description + "<div class=\"gray\">" + time + "</div>";
        description = description + "<div class=\"normal\">" + "推送通知：" + "</div>";
        description = description + "<div class=\"normal\">" + msgInfo.getCirculateMsgContent() + "</div>";
        //详情网址
        String url = "http://www.sdfey.com";
        //按钮内容
        String btntxt = "";
        map2.put("title", title);
        map2.put("description", description);
        map2.put("url", url);
        map2.put("btntxt", btntxt);
        //先将text的内容转化为jason字符串
        String mapJson2 = JSON.toJSONString(map2);
        Map<String, Object> map = new HashMap<String, Object>();
        //后期改动态
        map.put("touser", msgInfo.getWechatAccountCode());
        map.put("msgtype", "textcard");
        map.put("agentid", "1000028");
        map.put("textcard", mapJson2);
        //map转换为json形式
        String mapJson = JSON.toJSONString(map);
        //json串格式化，成为普通的string串
        String newString = StringEscapeUtils.unescapeJavaScript(mapJson);
        //但是普通的string串使用map<string,string>拼接，string两边会有双引号
        String s3 = newString.replace(":\"{", ":{");
        //修改，把第二层json外面多余的双引号去除
        String s4 = s3.replace("}\"", "}");
        String ans = "msg=" + s4;//给出的接口已msg=这个格式接受json格式的消息
        return ans;//返回的ans为最终所需要的串
    }

    public static TelMessageLog sendTelMessage3(MsgInfo msgInfo, Date appointmentTime, String appointmentClasses,
                                                ViewRJSSVO rjssvo, int flag) throws IOException {
        // 获取年  月  日
        ZoneId timeZone = ZoneId.systemDefault();
        LocalDate getDate = appointmentTime.toInstant().atZone(timeZone).toLocalDate();
        // 年
        int year = getDate.getYear();
        // 月
        int month = getDate.getMonthValue();
        // 日
        int day = getDate.getDayOfMonth();
        StringBuilder telMessage = new StringBuilder(rjssvo.getName() + "先生/女士" + year + "年" + month + "月" + day +
                "日是您预约来我院治疗的日子，请您于" + year + "年" + month + "月" + day + "日" + appointmentClasses +
                "根据医生电话交代的时间，带好住院证、检查等报告、门诊缴费发票，到住院部2-3号楼之间13号楼住院服务中心办手续，然后到2号楼2层21" +
                "病区：日间治疗中心护士站。如有特殊情况请联系您的主治医师或日间病房咨询电话：0512-67784215。" + "入院需知："+"【" + "1" +
                ".需要上麻醉者请确认已完成麻醉科门诊评估后再入院，局麻手术者无需麻醉门诊评估。" + "2.需要上麻醉者手术前一日22点之后禁食禁水，局麻手术者一般可正常饮食，具体以手术医生电话通知为准；" + "3" +
                ".特别提醒：如果手上有美甲请在来手术之前去除或者起码去除不同手的2个美甲。" + "4.手术当天需家属一人陪护，请不要携带任何贵重物品，更不要佩带任何首饰。" + "感谢您的理解与配合！"+"】");
        if (flag == 1) {
            telMessage = new StringBuilder("尊敬的" + rjssvo.getName() + "：您的预约已取消!");
        }

        TelMessageLog telMessageLog = new TelMessageLog();
        telMessageLog.setRequestMsg(telMessage.toString());
        telMessageLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        telMessageLog.setLinkPhoneTel(msgInfo.getLinkmanTel());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(
                "http://172.16.0.171:51008/sms/sms_send" +
                        ".php?service=cwgl&username=cwgl&password=feycwgl20220215&RPhone=" + telMessageLog.getLinkPhoneTel() + "&PostInfo=" + telMessageLog.getRequestMsg());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            telMessageLog.setResponseType("success");
            telMessageLog.setResponseMsg(result);
        } else {
            telMessageLog.setResponseType("fail");
        }
        httpClient.close();
        response.close();
        return telMessageLog;
    }
}
